<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="文章标题">
        <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="文章内容">
        <div id="div1"></div> </el-form-item
      ><el-form-item label="文章来源">
        <el-input
          v-model="form.stemfrom"
          placeholder="请输入文章来源"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from "@vue/reactivity";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { http } from "../../utils/http";
import E from "wangeditor";
import { onBeforeUnmount, onMounted } from "@vue/runtime-core";
const store = useStore();
const router = useRouter();

// 
const form = reactive({
  id: 0,
  createTime: "",
  title: "",
  stemfrom: "",
  content: "",
  author: store.state.msg.username,
});

// 设置富文本编辑器
let editor = ref(null)
onMounted(() => {
  editor = new E("#div1");
  editor.config.uploadImgServer = `http://192.168.0.222:3001/article/upload`
  editor.config.uploadFileName = 'img'
  editor.config.uploadImgHeaders = {
    authorization: "Bearer " + localStorage.getItem('token')
  }
  editor.config.placeholder = "编辑文章内容"
  editor.create();
});
onBeforeUnmount(() => {
  editor.destroy()
  editor = null
})
const submitForm = async () => {
  let date = new Date();
  form.createTime = date.getTime();
  form.id = date.getTime();
  form.content = editor.txt.html()
  try{
    let res = await http.post('/article/add', form)
    if( res.code === 200 ){
      router.push({
        path:'/admin/article'
      })
      ElMessage.success({
        type:'success',
        message: '发布成功'
      })
    }else{
      ElMessage.error({
        type:'error',
        message: '发布失败'
      })
    }
  }catch( err ){
    console.log(err);
  }
};
</script>

<style lang="scss" scoped>
.el-form {
  width: 70%;
  margin: 0 auto ;
  div:last-child {
    div {
      button {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
      }
    }
  }
}
</style>